<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { sensorByIdData } from "@T2/service/api.ts";
import { colorToRgba } from '@T2/utils/utils.ts';
import * as echarts from 'echarts';
import type { ECharts, EChartsOption, YAXisComponentOption, XAXisComponentOption, SeriesOption } from 'echarts';
import dayjs, { Dayjs } from 'dayjs';

const props = withDefaults(defineProps<{
  sensor: number;
  curDate?: Dayjs;
  name: string;
  colors?: string[];
}>(), {
  // curDate: () => dayjs(),
  colors: () => ['#06F8F9', '#F7C739', '#FFA8CC', '#73DEB3'],
});

let chartRef = ref<HTMLDivElement | null>(null);
let myChart: ECharts | null = null;
onMounted(() => {
  myChart = echarts.init(chartRef.value);
  beforeGetData();
});
watch(() => props.sensor, (nv, ov) => {
  beforeGetData();
});
const chartsData: EChartsOption = {
	backgroundColor: 'transparent',
  color: props.colors,
	grid: {
		left: "4%",
		right: "4%",
		bottom: "3%",
		top: 32,
		containLabel: true,
	},
  dataZoom: {
  	type: "inside",
    preventDefaultMouseMove: false,
  },
	legend: {
    show: false,
	},
	tooltip: {
		trigger: "axis",
    backgroundColor: '#105055',
    borderColor: '#34BBB7',
    textStyle: {
      color: '#B2B2B2',
      fontSize: 12,
    }
	},
	xAxis: {
		name: "",
		type: "time",
		axisLabel: {
			margin: 10,
			color: "#5CCCC5",
			fontSize: "10",
		},
    axisLine: {
      lineStyle: {
        color: 'rgba(92,204,197,0.3)',
      }
    },
    axisTick: {
      length: 3,
    },
		boundaryGap: [0, 0],
		splitNumber: 4,
	},
	yAxis: {
		name: "m³",
		type: "value",
		splitNumber: 3,
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: 'rgba(92,204,197,0.2)',
      }
    },
    nameTextStyle: {
      color: '#B2B2B2',
    },
    axisLabel: {
      color: '#5CCCC5',
      formatter: function (value) {
        if (value >= 10000) {
          return (value / 10000) + '万';
        }
        return value + '';
      }
    }
	},
  series: {
    type: "line",
    showSymbol: false,
    smooth: true,
    lineStyle: {
    	width: 1,
    },
  },
};

function beforeGetData() {
  if (!myChart) {
    return;
  }
  myChart.clear();
  getCurLine(props.sensor);
}

/* 实时曲线 */
interface DvalueType {
  conut: number;
  results: { create_time: string; data: string; _data?: number; id: number; }[];
  unit: string;
}
async function getCurLine(sensor: number) {
  let sdatas: DvalueType | undefined;
  let start = '', end = '';
  if (props.curDate) {
    start = dayjs(props.curDate).format("YYYY-MM-DD") + ' 00:00:00';
    end = dayjs(props.curDate).format("YYYY-MM-DD") + ' 23:59:59';
  } else {
    start = dayjs().subtract(1, 'day').format("YYYY-MM-DD HH:mm:ss");
    end = dayjs().format("YYYY-MM-DD HH:mm:ss");
  }
  await sensorByIdData({
  	method: "get",
  	id: sensor,
  	params: {
  		page: 1,
  		pagesize: 1000,
  		ordering: "create_time",
  		start,
  		end,
  	},
  }).then(res => {
    sdatas = res as unknown as DvalueType;
  });
  
  if (!sdatas) {
    return;
  }
  const yAxis = chartsData.yAxis as YAXisComponentOption;
  yAxis.name = sdatas.unit;
  const xAxis = chartsData.xAxis as XAXisComponentOption;
  xAxis.min = start;
  xAxis.max = end;
  /* 没招了，就是没属性splitNumber */
  (xAxis as any).splitNumber = 4;
  const axisLabel = xAxis.axisLabel as XAXisComponentOption['axisLabel'];
  /* 没招了，就是没属性formatter */
  (axisLabel as any).formatter = function (value: Dayjs) {
  	return dayjs(value).format('HH:mm');
  };
  (chartsData.tooltip as any).formatter = function (par: any) {
    let time = par.length && dayjs(par[0].data[0]).format("HH:mm");
    let res = time + '<br />';
    par.forEach((ser: any) => {
    	res = res
    		+ `<span style="display:inline-block;margin-bottom:1px;margin-right:4px;border-radius:5px;width:5px;height:5px;background-color:${ser.color};"></span>`
    		+ ser.seriesName
        + `<span style="margin-left:10px;font-size:14px;font-family:YouSheBiaoTiHei;color:#06F8F9">${ser.data[1]}</span>`
    		+ `<span style="margin-left:2px;font-size:10px">${yAxis.name}</span>`
    		+ '<br />'
    });
    return res;
  }
  initLineOptions(sdatas)
}
function initLineOptions(res: DvalueType) {
  const series = chartsData.series as SeriesOption;
  series.name = props.name || '';
	const { results } = res;
  results.forEach(item => item._data = +item.data);
  series.data = results.map((item) => [
  	item.create_time,
  	(item._data)!.toFixed(2),
  ]);
  myChart!.setOption(chartsData, true);
}
</script>

<template>
  <div class="container-echarts" ref="chartRef"></div>
</template>

<style lang="scss" scoped>
.container-echarts {
  width: 100%;
  height: 100%;
}
</style>